﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using ChangDiTools.Tool;
using AcAp = Autodesk.AutoCAD.ApplicationServices.Application;
namespace ChangDiTools.Demo {
    public class Layers {
        [CommandMethod("CreateLayer")]
        public static void CreateLayer() {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            string layerName = "";
            using (Transaction tr = db.TransactionManager.StartTransaction()) {
                while (layerName=="")
                {
                    PromptResult pr = ed.GetString("\n请输入图层名称");
                    if(pr.Status!=PromptStatus.OK) return;
                    try
                    {
                        //验证输入字符串是否符合符号表命名规则
                        SymbolUtilityServices.ValidateSymbolName(pr.StringResult,false);
                        layerName = pr.StringResult;
                        if (db.AddLayer(layerName) != ObjectId.Null)
                        {
                            PromptIntegerResult pir = ed.GetInteger("\n请输入层的颜色值");
                            if(pir.Status!=PromptStatus.OK) return;
                            db.SetLayerColor(layerName, (short) pir.Value);
                            db.SetCurrentLayer(layerName);
                            break;
                        }
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception e)
                    {
                        ed.WriteMessage(e.Message);
                    }
                }
                tr.Commit();
            }
        }

        [CommandMethod("DelRedLayer")]
        public void DelRedLayer()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (var tr=db.TransactionManager.StartTransaction())
            {
                var redLayers = (from layer in db.GetAllLayer()
                    where layer.Color == Color.FromColorIndex(ColorMethod.ByAci, 1)
                    select layer.Name).ToList();
                redLayers.ForEach(layer=>db.DeleteLayer(layer));
                tr.Commit();
            }
        }
    }
}
